<?php

/**
 * element actions.
 *
 * @package    ems1
 * @subpackage element
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class elementActions extends sfActions
{
    public function executeIndex(sfWebRequest $request)
    {
        $this->ems_elements = $this->getRoute()->getObjects();
    }

    public function executeShow(sfWebRequest $request)
    {
        $element = $this->getRoute()->getObject();

        return $this->renderPartial('show'.$element->getType()->getType(), array ('element' => $element));
    }

    public function executeNew(sfWebRequest $request)
    {
        $type = Doctrine::getTable('EmsElementType')->find(array($request->getParameter('type_id')));
        $section = Doctrine::getTable('EmsSection')->find(array($request->getParameter('section_id')));

        $counter = $section->getPositionCount() + 1;

        $element = new EmsElement();
        $element->setType($type);
        $element->setSection($section);

        $form = new EmsElementForm($element,array('portal_id' => $section->getPortal()->getId()));

        return $this->renderPartial('form'.$element->getType()->getType(), array(
                            'form' => $form, 'type' => $type, 'section' => $section)
                        );
    }

    public function executeCreate(sfWebRequest $request)
    {
        $this->forward404Unless(
                $type = Doctrine::getTable('EmsElementType')->find(array($request->getParameter('type_id'))),
                sprintf('Object type does not exist (%s).', $request->getParameter('type_id'))
                );
        $this->forward404Unless(
                $section = Doctrine::getTable('EmsSection')->find(array($request->getParameter('section_id'))),
                sprintf('Object section does not exist (%s).', $request->getParameter('type_id'))
                );

        $counter = $section->getPositionCount() + 1;

        $element = new EmsElement();
        $element->setType($type);
        $element->setSection($section);

        $form = new EmsElementForm($element,array('portal_id' => $section->getPortal()->getId()));

        $valid = $this->processForm($request, $form, $counter);

        if(!$valid){
            return $this->renderPartial('form'.$element->getType()->getType(),
                    array('form' => $form, 'type' => $type, 'section' => $section));
        } else {
            return sfView::NONE;
        }
    }

    public function executeEdit(sfWebRequest $request)
    {
        $element = $this->getRoute()->getObject();

        if($element->getSectionId()){
            $form = new EmsElementForm($element, array('portal_id' => $element->getSection()->getPortal()->getId())); //'counter'=> $element->getSection()->getPositionCount()
        } elseif ($element->getHeaderId()) {
            $form = new EmsElementForm($element, array(
                'portal_id' => $element->getHeader()->getPortal()->getId(),
                'counter'   => $element->getHeader()->getElements()->count()
                ));
        } elseif ($element->getFooterId()) {
            $form = new EmsElementForm($element, array(
                'portal_id' => $element->getFooter()->getPortal()->getId(),
                'counter'   => $element->getFooter()->getElements()->count()
                ));
        }
        return $this->renderPartial('form'.$element->getType()->getType(), array(
                        'form' => $form, 'type' => $element->getType(), 'section' => $element->getSection())
                    );
    }

    public function executeUpdate(sfWebRequest $request)
    {
        $element = $this->getRoute()->getObject();

        if($element->getSectionId()){
            $form = new EmsElementForm($element, array('portal_id' => $element->getSection()->getPortal()->getId()));
        } elseif ($element->getHeaderId()) {
            $form = new EmsElementForm($element, array(
                'portal_id' => $element->getHeader()->getPortal()->getId(),
                'counter'   => $element->getHeader()->getElements()->count()
                ));
        } elseif ($element->getFooterId()) {
            $form = new EmsElementForm($element, array(
                'portal_id' => $element->getFooter()->getPortal()->getId(),
                'counter'   => $element->getFooter()->getElements()->count()
                ));
        }

        $valid = $this->processForm($request, $form, $element->getPosition());

        if(!$valid){
            return $this->renderPartial('form'.$element->getType()->getType(),
                    array('form' => $form, 'type' => $element->getType(), 'section' => $element->getSection()));
        } else {
            return sfView::NONE;
        }
    }

    protected function processForm(sfWebRequest $request, sfForm $form, $oldpos)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        $valid = $form->isValid();
        if ($valid)
        {
            $audit = new EmsAudit();

            if($form->getObject()->isNew()){
                $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear elemento'));
            } else {
                $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar elemento'));
            }

            $element = $form->save();

            $user = $this->getUser()->getGuardUser();

            $audit->setUser($user);
            $audit->setObjectId($element->getId());

            if($element->getSectionId()){
                $audit->setPortal($element->getSection()->getPortal());
            } elseif ($element->getHeaderId()) {
                $audit->setPortal($element->getHeader()->getPortal());
                $element->getHeader()->orderForRender($element, $oldpos);
            } elseif ($element->getFooterId()) {
                $audit->setPortal($element->getFooter()->getPortal());
                $element->getFooter()->orderForRender($element, $oldpos);
            }

            $audit->save();

            return $this->renderPartial('multiUpdate', array ('element' => $element));
        }
        return $valid;
    }
    
    public function executeAddMenuOptionForm(sfWebRequest $request)
    {
        $this->forward404unless($request->isXmlHttpRequest());
        $num = $request->getParameter('num');

        if($element = Doctrine::getTable('EmsElement')->find(array($request->getParameter('id')))){
            $form = new EmsElementForm($element, array('portal_id' => $request->getParameter('portal_id')));
        }else{
            $type = Doctrine::getTable('EmsElementType')->find($request->getParameter('type_id'));
            $element = new EmsElement();
            $element->setType($type);
            $form = new EmsElementForm($element, array('portal_id' => $request->getParameter('portal_id')));
        }

        $form->addMenuOption($num);

        return $this->renderPartial('addOption',array('form' => $form, 'num' => $num));
    }

    public function executeAddFeatureForm(sfWebRequest $request)
    {
        $this->forward404unless($request->isXmlHttpRequest());
        $num = $request->getParameter('num');

        if($element = Doctrine::getTable('EmsElement')->find(array($request->getParameter('id')))){
            $form = new EmsElementForm($element, array('portal_id' => $element->getSection()->getPortalId()));
        }else{
            $type = Doctrine::getTable('EmsElementType')->find(array($request->getParameter('type_id')));
            $element = new EmsElement();
            $element->setType($type);
            $form = new EmsElementForm($element, array('portal_id' => $request->getParameter('portal_id')));
        }

        $form->addFeatureForm($num);

        return $this->renderPartial('addFeature',array('form' => $form, 'num' => $num));
    }

    public function executeAddFormFieldForm(sfWebRequest $request)
    {
        $this->forward404unless($request->isXmlHttpRequest());
        $num = $request->getParameter('num');

        if($element = Doctrine::getTable('EmsElement')->find(array($request->getParameter('id')))){
            $form = new EmsElementForm($element, array('portal_id' => $element->getSection()->getPortalId()));
        }else{
            $type = Doctrine::getTable('EmsElementType')->find(array($request->getParameter('type_id')));
            $element = new EmsElement();
            $element->setType($type);
            $form = new EmsElementForm($element, array('portal_id' => $request->getParameter('portal_id')));
        }

        $form->addFormFieldForm($num);

        return $this->renderPartial('addFormField',array('form' => $form, 'num' => $num));
    }

    public function executeGetFeatures(sfWebRequest $request)
    {
        $this->getResponse()->setContentType('application/json');

        $string = $request->getParameter('q');

        $limit = $request->getParameter('limit');

        $portal_id = $request->getParameter('portal_id');

        $type_id = $request->getParameter('type_id');

        $results = Doctrine::getTable('EmsContent')->getPortalEnabledAndPublishedContentsFilteredByTypeByTitleLike($string, $limit, $portal_id, $type_id);

        $features = array();

        foreach ($results as $feature) {
            $features[$feature->getId()] = $feature->getTitle();
        }

        return $this->renderText(json_encode($features));
    }

    public function executeGetSections(sfWebRequest $request)
    {
        $this->getResponse()->setContentType('application/json');

        $string = $request->getParameter('q');

        $limit = $request->getParameter('limit');

        $portal_id = $request->getParameter('portal_id');

        $results = Doctrine::getTable('EmsSection')->getEnabledAndPublishedPortalSectionsByTitleLike($string, $limit, $portal_id);

        $sections = array();

        foreach ($results as $section) {
            $sections[$section->getId()] = $section->getTitle();
        }

        return $this->renderText(json_encode($sections));
    }

    public function executeMultiupdate(sfWebRequest $request)
    {
        $portal = $this->getRoute()->getObject();

        return $this->renderPartial('multiUpdate', array('portal' => $portal));
    }

    public function  executeShowFormRegisters(sfWebRequest $request)
    {
        $element = $this->getRoute()->getObject();

        $fields = $element->getForm()->getFields();
        
        $registers = $element->getForm()->getRegisters();

        return $this->renderPartial('showFormRegisters', array(
            'element' => $element,
            'fields' => $fields,
            'registers' => $registers
        ));
    }

    /*
     * Esta función permite exportar los registros asociados a un formulario
     * en un archivo excel (.xls)
     */
    public function executeExportFormRegisters(sfWebRequest $request)
    {
        $this->element = $this->getRoute()->getObject();
        $this->registers = $this->element->getForm()->getRegisters();
        $this->fields = $this->element->getForm()->getFields();

        $this->getResponse()->clearHttpHeaders();

        $this->getResponse()->setHttpHeader('Content-Type', 'application/vnd.ms-excel; charset=utf-8');

        $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename=registros-formulario-'.$this->element->getSlug().'.xls');
        
        $this->getResponse()->setHttpHeader('Pragma', 'no-cache');

        $this->getResponse()->setHttpHeader('Expires', '0');

        $this->setLayout('minimal');
    }

    public function executeTempFileUpload(sfWebRequest $request){

        $element_type = $this->getRoute()->getObject();

        $element = new EmsElement();

        $element->setType($element_type);

        $element->setSectionId($request->getParameter('section_id'));

        $form = new EmsElementForm($element, array('portal_id' => $request->getParameter('portal_id')));

        $files = $request->getFiles($form->getName());

        $json_response = array();

        $file = null;

        $type = $element_type->getType();

        switch ($element_type->getType()) {
            case 'Banner':
                $i = 0;
                foreach ($files['Banner']['Images'] as $temp) {
                    if(isset($temp['tmp_file'])){

                       $file = $temp['tmp_file'];

                        $banner_image = $form->getEmbeddedForm('Banner')->getEmbeddedForm('Images')->getEmbeddedForm($i)->getObject();

                        $validator = new jsValidatorImage(array(
                                            'mime_types' => array('image/jpeg'),
                                            'trim'       => true,
                                            'path'       => sfConfig::get('sf_upload_dir').'/portal_'.$request->getParameter('portal_id').'/temp_files/',
                                            'required'   => false,
                                            'max_size'   => '1048576',
                                            'minx'       => $banner_image->getSize()->getWidth(),
                                            'maxx'       => $banner_image->getSize()->getWidth(),
                                            'miny'       => 1,
                                            'maxy'       => $banner_image->getSize()->getHeight()
                                        ), array(
                                            'required'   => 'Debe indicar el archivo de formato .JPEG a ser cargado.',
                                            'max_size'   => 'La imagen excede el peso máximo de archivo permitido, 1 MB.',
                                            'mime_types' => 'Tipo de archivo invalido (%mime_type%), el archivo a cargar debe ser de tipo JPEG'
                                        ));

                        try {

                            $validator->clean($file);

                        } catch (sfValidatorError $e) {

                            $json_response['valid'] = false;

                            $json_response['error_message'] = $e->getMessage();

                            return $this->renderText(json_encode($json_response));
                        }

                        $json_response['valid'] = true;

                        $json_response['file_name'] = $file['name'];

                        $json_response['temp_file'] = Util::saveTempFile($file, $request->getParameter('portal_id'));

                        $json_response['size'] = $file['size'];

                        $json_response['type'] = $file['type'];

                        $json_response['portal_id'] = $request->getParameter('portal_id');
                    }
                    $i++;
                }
                break;
            case 'Menu':
                if(isset($files['Menu']['tmp_bullet'])){

                    $file = $files['Menu']['tmp_bullet'];

                    $validator = new jsValidatorImage(array(
                                        'mime_types' => array('image/jpeg'),
                                        'trim'       => true,
                                        'path'       => sfConfig::get('sf_upload_dir').'/portal_'.$request->getParameter('portal_id').'/temp_files/',
                                        'required'   => true,
                                        'max_size'   => '1048576',
                                        'minx'       => 30,
                                        'maxx'       => 30,
                                        'miny'       => 30,
                                        'maxy'       => 30
                                    ), array(
                                        'required'   => 'Debe indicar el archivo de formato .JPEG a ser cargado.',
                                        'max_size'   => 'La imagen excede el peso máximo de archivo permitido, 1 MB.',
                                        'mime_types' => 'Tipo de archivo invalido (%mime_type%), el archivo a cargar debe ser de tipo JPEG'
                                    ));

                    try {

                        $validator->clean($file);

                    } catch (sfValidatorError $e) {

                        $json_response['valid'] = false;

                        $json_response['error_message'] = $e->getMessage();

                        return $this->renderText(json_encode($json_response));
                    }

                    $json_response['valid'] = true;

                    $json_response['file_name'] = $file['name'];

                    $json_response['temp_file'] = Util::saveTempFile($file, $request->getParameter('portal_id'));

                    $json_response['size'] = $file['size'];

                    $json_response['type'] = $file['type'];

                    $json_response['portal_id'] = $request->getParameter('portal_id');
                }
                break;
            case 'FeaturesBlock':
                if(isset($files['FeaturesBlock']['tmp_bullet']) || isset($files['FeaturesBlock']['tmp_bullet_new'])){

                    $file = isset($files['FeaturesBlock']['tmp_bullet']) ?
                            $files['FeaturesBlock']['tmp_bullet'] : $files['FeaturesBlock']['tmp_bullet_new'];

                    $validator = new jsValidatorImage(array(
                                        'mime_types' => array('image/jpeg'),
                                        'trim'       => true,
                                        'path'       => sfConfig::get('sf_upload_dir').'/portal_'.$request->getParameter('portal_id').'/temp_files/',
                                        'required'   => true,
                                        'max_size'   => '1048576',
                                        'minx'       => (isset($files['FeaturesBlock']['tmp_bullet']) ? 30 : 60),
                                        'maxx'       => (isset($files['FeaturesBlock']['tmp_bullet']) ? 30 : 60),
                                        'miny'       => 30,
                                        'maxy'       => 30
                                    ), array(
                                        'required'   => 'Debe indicar el archivo de formato .JPEG a ser cargado.',
                                        'max_size'   => 'La imagen excede el peso máximo de archivo permitido, 1 MB.',
                                        'mime_types' => 'Tipo de archivo invalido (%mime_type%), el archivo a cargar debe ser de tipo JPEG'
                                    ));

                    try {

                        $validator->clean($file);

                    } catch (sfValidatorError $e) {

                        $json_response['valid'] = false;

                        $json_response['error_message'] = $e->getMessage();

                        return $this->renderText(json_encode($json_response));
                    }

                    $json_response['valid'] = true;

                    $json_response['file_name'] = $file['name'];

                    $json_response['temp_file'] = Util::saveTempFile($file, $request->getParameter('portal_id'));

                    $json_response['size'] = $file['size'];

                    $json_response['type'] = $file['type'];

                    $json_response['portal_id'] = $request->getParameter('portal_id');
                }
                break;
            default:
                break;
        }
        return $this->renderText(json_encode($json_response));
    }
}
